'use client';

import { useState, useEffect } from 'react';
import { 
  Box, 
  Container, 
  Typography, 
  Paper, 
  Breadcrumbs,
  Button,
  Chip,
  Divider,
  CircularProgress,
  Alert,
  Grid
} from '@mui/material';
import Navbar from '@/components/Navbar';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import ShareIcon from '@mui/icons-material/Share';
import DownloadIcon from '@mui/icons-material/Download';
import CalendarTodayIcon from '@mui/icons-material/CalendarToday';
import SourceIcon from '@mui/icons-material/Source';
import LaunchIcon from '@mui/icons-material/Launch';
import axios from 'axios';
import api from '@/utils/api';

interface Policy {
  id: number;
  title: string;
  summary: string;
  content: string;
  source: string;
  publishDate: string | null;
  url: string;
  category: string;
  tags: string[];
  keyPoints: string[];
  requirements: string[];
}

interface RelatedPolicy {
  id: number;
  title: string;
  summary: string;
  source: string;
  publishDate: string | null;
  category: string;
  tags: string[];
}

export default function PolicyDetailPage() {
  const params = useParams();
  const policyId = typeof params.id === 'string' ? parseInt(params.id, 10) : 0;
  
  const [policy, setPolicy] = useState<Policy | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string>('');
  const [relatedPolicies, setRelatedPolicies] = useState<RelatedPolicy[]>([]);

  useEffect(() => {
    const fetchPolicy = async () => {
      try {
        setLoading(true);
        const response = await api.get(`/api/enterprise/policies/${policyId}`);
        
        if (response.data.success) {
          setPolicy(response.data.policy);
          setRelatedPolicies(response.data.relatedPolicies || []);
        } else {
          setError(response.data.message || '获取政策数据失败');
        }
        setLoading(false);
      } catch (err) {
        console.error('获取政策详情失败:', err);
        setError('获取政策数据失败，请稍后再试');
        setLoading(false);
      }
    };

    if (policyId) {
      fetchPolicy();
    } else {
      setError('无效的政策ID');
      setLoading(false);
    }
  }, [policyId]);

  if (loading) {
    return (
      <Box sx={{ minHeight: '100vh', bgcolor: '#f5f5f5' }}>
        <Navbar />
        <Container maxWidth="lg" sx={{ py: 4 }}>
          <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '60vh' }}>
            <CircularProgress />
          </Box>
        </Container>
      </Box>
    );
  }

  if (error || !policy) {
    return (
      <Box sx={{ minHeight: '100vh', bgcolor: '#f5f5f5' }}>
        <Navbar />
        <Container maxWidth="lg" sx={{ py: 4 }}>
          <Alert severity="error" sx={{ mb: 3 }}>
            {error || '政策信息加载失败'}
          </Alert>
          <Button 
            startIcon={<ArrowBackIcon />} 
            component={Link} 
            href="/enterprise/policies"
          >
            返回政策列表
          </Button>
        </Container>
      </Box>
    );
  }

  return (
    <Box sx={{ minHeight: '100vh', bgcolor: '#f5f5f5' }}>
      <Navbar />
      
      <Container maxWidth="lg" sx={{ py: 4 }}>
        {/* 面包屑导航 */}
        <Breadcrumbs sx={{ mb: 3 }}>
          <Link href="/" style={{ textDecoration: 'none', color: 'inherit' }}>
            首页
          </Link>
          <Link href="/enterprise" style={{ textDecoration: 'none', color: 'inherit' }}>
            企业服务
          </Link>
          <Link href="/enterprise/policies" style={{ textDecoration: 'none', color: 'inherit' }}>
            惠企政策
          </Link>
          <Typography color="text.primary">{policy.title}</Typography>
        </Breadcrumbs>
        
        {/* 返回按钮 */}
        <Button 
          startIcon={<ArrowBackIcon />} 
          component={Link} 
          href="/enterprise/policies"
          sx={{ mb: 3 }}
        >
          返回政策列表
        </Button>
        
        <Grid container spacing={3}>
          <Grid item xs={12} md={8}>
            {/* 政策详情 */}
            <Paper sx={{ p: 4, mb: 3 }}>
              <Typography variant="h4" component="h1" gutterBottom>
                {policy.title}
              </Typography>
              
              <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1, mb: 3 }}>
                <Chip size="small" label={policy.category} color="primary" />
                {policy.tags.map((tag, index) => (
                  <Chip key={index} size="small" label={tag} variant="outlined" />
                ))}
              </Box>
              
              <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 2, mb: 3, color: 'text.secondary' }}>
                <Box sx={{ display: 'flex', alignItems: 'center' }}>
                  <CalendarTodayIcon fontSize="small" sx={{ mr: 0.5 }} />
                  <Typography variant="body2">发布日期: {policy.publishDate || '未知'}</Typography>
                </Box>
                <Box sx={{ display: 'flex', alignItems: 'center' }}>
                  <SourceIcon fontSize="small" sx={{ mr: 0.5 }} />
                  <Typography variant="body2">发布单位: {policy.source}</Typography>
                </Box>
              </Box>
              
              <Divider sx={{ my: 3 }} />
              
              {/* 政策摘要 */}
              <Box sx={{ mb: 3, p: 2, bgcolor: '#f9f9f9', borderRadius: 1 }}>
                <Typography variant="h6" gutterBottom>
                  政策摘要
                </Typography>
                <Typography variant="body1">
                  {policy.summary}
                </Typography>
              </Box>
              
              {/* 政策内容 */}
              <Typography variant="h6" gutterBottom>
                政策原文
              </Typography>
              <Box 
                dangerouslySetInnerHTML={{ __html: policy.content }} 
                sx={{ 
                  '& p': { mb: 2 },
                  '& h3': { mt: 3, mb: 2, fontSize: '1.2rem', fontWeight: 'bold' }
                }}
              />
              
              <Box sx={{ mt: 4, display: 'flex', justifyContent: 'space-between' }}>
                <Button 
                  variant="contained"
                  color="primary"
                  startIcon={<LaunchIcon />}
                  component="a"
                  href={policy.url}
                  target="_blank"
                  rel="noopener"
                >
                  查看原文链接
                </Button>
                <Box>
                  <Button 
                    startIcon={<ShareIcon />}
                    sx={{ mr: 1 }}
                  >
                    分享
                  </Button>
                  <Button 
                    startIcon={<DownloadIcon />}
                  >
                    下载
                  </Button>
                </Box>
              </Box>
            </Paper>
          </Grid>
          
          <Grid item xs={12} md={4}>
            {/* 政策要点 */}
            {policy.keyPoints && policy.keyPoints.length > 0 && (
              <Paper sx={{ p: 3, mb: 3 }}>
                <Typography variant="h6" gutterBottom>
                  政策要点
                </Typography>
                <Box component="ul" sx={{ pl: 2 }}>
                  {policy.keyPoints.map((point, index) => (
                    <Typography component="li" key={index} sx={{ mb: 1 }}>
                      {point}
                    </Typography>
                  ))}
                </Box>
              </Paper>
            )}
            
            {/* 申请条件 */}
            {policy.requirements && policy.requirements.length > 0 && (
              <Paper sx={{ p: 3, mb: 3 }}>
                <Typography variant="h6" gutterBottom>
                  申请条件
                </Typography>
                <Box component="ul" sx={{ pl: 2 }}>
                  {policy.requirements.map((req, index) => (
                    <Typography component="li" key={index} sx={{ mb: 1 }}>
                      {req}
                    </Typography>
                  ))}
                </Box>
              </Paper>
            )}
            
            {/* 相关政策 */}
            {relatedPolicies.length > 0 && (
              <Paper sx={{ p: 3 }}>
                <Typography variant="h6" gutterBottom>
                  相关政策
                </Typography>
                {relatedPolicies.map((related) => (
                  <Box key={related.id} sx={{ mb: 2, pb: 2, borderBottom: '1px solid #eee' }}>
                    <Link 
                      href={`/enterprise/policies/${related.id}`} 
                      style={{ textDecoration: 'none', color: 'inherit' }}
                    >
                      <Typography variant="subtitle1" sx={{ fontWeight: 'medium', color: 'primary.main' }}>
                        {related.title}
                      </Typography>
                    </Link>
                    <Typography variant="body2" color="text.secondary">
                      {related.publishDate || '未知'} · {related.source}
                    </Typography>
                  </Box>
                ))}
              </Paper>
            )}
          </Grid>
        </Grid>
      </Container>
    </Box>
  );
} 